{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "6ae9ca25-694d-4643-8d88-4f72f908b466",
   "metadata": {},
   "source": [
    "# download temperature\n",
    "\n",
    "download temperature data for sample region\n",
    "\n",
    "Author: Yuqi Chen\n",
    "\n",
    "Date: 2023/11/13\n",
    "\n",
    "Data Source: [Daymet v4](https://developers.google.com/earth-engine/datasets/catalog/NASA_ORNL_DAYMET_V4)\n",
    "\n",
    "* spatial resolution: 1 km\n",
    "* spatial range: sample region in shortgrass steep, clip to $[-102,-100,35,37]$\n",
    "* time range: 1901-2021, filter to $[2001,2020]$\n",
    "* time resolution: daily\n",
    "\n",
    "Key Parameters:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2ac76a48-c914-471e-bc74-84519f641f69",
   "metadata": {
    "tags": []
   },
   "source": [
    "## Start up"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0b023e69-5e6c-4914-9845-1e1249601c44",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "import ee\n",
    "import geemap\n",
    "geemap.set_proxy(port=7890)\n",
    "Map = geemap.Map()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7107a505-49f6-43f1-b0cb-9017bf18a268",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# set the start date\n",
    "import os\n",
    "\n",
    "# PARA1: start date\n",
    "last_date = \"2001-01-01\"\n",
    "\n",
    "# if download cruptted, start from the newest date\n",
    "vFiles = os.listdir(\"./data\")\n",
    "if len(vFiles) != 0:\n",
    "    last_file = vFiles[-1]\n",
    "    last_date = \"{0}-{1}-{2}\".format(last_file[0:4],last_file[4:6],last_file[6:8])\n",
    "print(\"Start downloading from {0}\".format(last_date))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6d393ea5-a682-48bd-9b06-897032d36474",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# PARA2: set imageCollection\n",
    "Cols = ee.ImageCollection(\"NASA/ORNL/DAYMET_V4\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fd779615-83cc-4515-b4f6-5edb72859174",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# PARA3: set const\n",
    "init_path = {\n",
    "    \"shp\":r\"\",\n",
    "    \"dir_out\": \"./data\",\n",
    "}\n",
    "# end date: not included\n",
    "# band: band name for download\n",
    "# miao and miao_fail: information for miao alert\n",
    "init_const = {\n",
    "    \"start_date\":last_date,\n",
    "    \"end_date\":\"2021-01-01\",\n",
    "    \"region\": [-102,35,-100,37],\n",
    "    \"band\": [\"tmax\",\"tmin\"],\n",
    "    \"miao\": \"finish downloading temperature\",\n",
    "    \"miao_fail\": \"fail downloading temperature\"\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2ba8495a-ca8a-4781-9015-c063f512f4a5",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# roi = geemap.shp_to_ee(init_path[\"shp\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "745e6dd3-def3-4b17-a78d-c106d94b6c0e",
   "metadata": {},
   "source": [
    "## Filter Data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c0931aa7-5210-494a-b1e7-8d9072521e5e",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "roi_box = ee.Geometry.Rectangle(init_const[\"region\"],\"EPSG:4326\",False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "32d4c3ee-44b5-4b09-b1b6-66cd2563b12d",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Map.addLayer(roi,{},\"sgs\")\n",
    "Map.addLayer(roi_box,{},\"bounds\")\n",
    "Map.centerObject(roi_box,8)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3d8b244e-f2c1-482d-9b30-0b975b319580",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "Map"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f37ca722-0861-469f-aae2-15902de70b3d",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# function to clip region to box we set\n",
    "def clip_region(image):\n",
    "    image = image.clip(roi_box)\n",
    "    return image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bcfadb2b-e75c-4959-b24a-fa7330608ef0",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# function to resample to target resolution, to make images from different source \n",
    "# in the same size.\n",
    "def resample_1km(image):\n",
    "    image = image.resample('bilinear').reproject(crs = \"EPSG:4326\", scale = 1000)\n",
    "    return image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a3e0cb49-d5a4-4a1c-851e-4649f1ab9f85",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# calculate new band from image bands\n",
    "def get_tmean(image):\n",
    "    tmean = image.expression(\n",
    "        '(Tmin + Tmax) / 2',\n",
    "        {\n",
    "            'Tmin':image.select(\"tmin\"),\n",
    "            'Tmax':image.select(\"tmax\")\n",
    "        }\n",
    "    ).rename(\"tmean\")\n",
    "    return image.addBands(tmean,[\"tmean\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dcc9c455-587f-4114-8dc8-e8e23c41ca37",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# check the default figure size in sample region\n",
    "\n",
    "\n",
    "# imgCols = Cols \\\n",
    "#     .filterDate(init_const[\"start_date\"],init_const[\"end_date\"]) \\\n",
    "#     .filterBounds(roi_box) \\\n",
    "#     .select(init_const[\"band\"]) \\\n",
    "#     .map(clip_region)\n",
    "\n",
    "# tmp_image = imgCols.limit(1).first()\n",
    "# tmp_image"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e6066cc2-623f-47e9-b5e1-07b8d9c0e373",
   "metadata": {},
   "source": [
    "The default figure size is (177x216), so we need to use resample method to resize to (224x223)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ca319749-299c-40e2-95e6-ed15ec1e1bdc",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "imgCols = Cols \\\n",
    "    .filterDate(init_const[\"start_date\"],init_const[\"end_date\"]) \\\n",
    "    .filterBounds(roi_box) \\\n",
    "    .select(init_const[\"band\"]) \\\n",
    "    .map(get_tmean) \\\n",
    "    .map(resample_1km) \\\n",
    "    .map(clip_region) "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e69930c0-25b7-4f0f-a6bb-525429b3b473",
   "metadata": {},
   "source": [
    "### Check Results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8d219b5d-9221-46f7-9d0d-d9bf2ddb5e00",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# check image size\n",
    "tmp_image = imgCols.limit(1).first()\n",
    "tmp_image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5bf9cf19-a052-414c-b84d-fe0b431e8008",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# get min and max value in pixels, for visual setting\n",
    "geemap.image_stats(tmp_image, scale = 1000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "08a67490-eab6-4484-abf9-4805a83da1eb",
   "metadata": {},
   "outputs": [],
   "source": [
    "# set band name, min and max\n",
    "Map.addLayer(tmp_image,{\"Band\":\"tmean\",\"min\":-7,\"max\":-3},\"clipped\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8546eeef-785b-46ef-9b5c-78d637f1cb3c",
   "metadata": {},
   "source": [
    "## Downloading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ce4a5165-697b-4db3-a713-12c13b44fe0f",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "geemap.download_ee_image_collection(imgCols,init_path[\"dir_out\"],scale = 1000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "72e13df4-fe02-4695-8852-11ade312f2ef",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# use miao alert to send notice to wechat\n",
    "# PARA4: get total image number from above code cell\n",
    "image_number = 7300\n",
    "# miao code\n",
    "miao_code = \"tnLiHyP\"\n",
    "\n",
    "if len(os.listdir(init_path[\"dir_out\"])) == image_number:\n",
    "    text = init_const[\"miao\"]\n",
    "else:\n",
    "    text = init_const[\"miao_fail\"]\n",
    "        \n",
    "from urllib import request, parse\n",
    "import time\n",
    "import json\n",
    "\n",
    "\n",
    "page = request.urlopen(\"http://miaotixing.com/trigger?\" + parse.urlencode({\"id\":miao_code, \"text\":text, \"type\":\"json\"}))\n",
    "result = page.read()\n",
    "jsonObj = json.loads(result)\n",
    "if (jsonObj[\"code\"] == 0):\n",
    "    print(\"成功\")\n",
    "else:\n",
    "    print(\"失败，错误代码：\" + str(jsonObj[\"code\"]) + \"，描述：\" + jsonObj[\"msg\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8b71dc89-09ae-4e8a-87be-5c3d2f3b7e03",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
